<?php


use Medoo\Medoo;
use QL\QueryList;
/**
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once realpath('..') . '/vendor/autoload.php';
$config = include 'database.php';

echo '爬虫开始' . PHP_EOL;
/*
$client = new GuzzleHttp\Client();
$res = $client->request('GET',
    'https://ap.nissan-api.net/v2/dealers?size=200&lat=39.91092462465681&long=116.4133836971231&serviceFilterType=AND&include=openingHours'
    , [
        'headers' => [
            'apiKey' => 'JAdOBlxEg2wRRQKJus8D9R5kjvDZ78Ba',
            'clientKey' => 'lVqTrQx76FnGUhV6AFi7iSy9aXRwLIy7',
            'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36'
        ]
    ]);
*/
$res = QueryList::get('https://ap.nissan-api.net/v2/dealers?size=200&lat=39.91092462465681&long=116.4133836971231&serviceFilterType=AND&include=openingHours'
,[
    'size'=>200,
    'lat'=>'39.91092462465681',
    'long'=>'116.4133836971231',
    'serviceFilterType'=>'AND',
    'include'=>'openingHours'
],[
    'headers' => [
        'apiKey' => 'JAdOBlxEg2wRRQKJus8D9R5kjvDZ78Ba',
        'clientKey' => 'lVqTrQx76FnGUhV6AFi7iSy9aXRwLIy7',
        'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36'
    ]
]);
$html = $res->getHtml();
$data = json_decode($html, true);


$db = new Medoo($config);
$db->delete('tDealer', ['sBrand' => '英菲尼迪']);


foreach ($data['dealers'] as $item) {
    $db->insert('tDealer', [
        'sDealerName' => $item['name'],
        'nBrandID' => $item['dealerId'],
        'sBrand' => '英菲尼迪',
        'sProvince' => $item['address']['state'],
        'sCity' => $item['address']['city'],
        'sAddress' => $item['address']['addressLine1'],
        'sSaleCall' => $item['contact']['phone'],
        'sLatitude' => $item['geolocation']['latitude'],
        'sLongitude' => $item['geolocation']['longitude'],
        'dUpdateTime' => Medoo::raw('now()'),
        'sManufacturer' => '英菲尼迪',
    ]);
    echo "{$item['name']}完成" . PHP_EOL;
}
echo '爬虫结束' . PHP_EOL;